from lxml import etree
from util.selenium.webdriver.common.by import By

# from base.base_method import bm
# from util.db_operate import SaveData, GetTechList
from spider_data.spiderBaseMethod import bm
from util.g import g


# from util.handle_list import get_first, join_and_repalce, get_first_and_replace
# from util.handle_ps import handle_ps

# TODO 2018  https://innocomreport2.chinatorch.org.cn/xinnocommgr/reportdeal/CertificateValidity/showDetails.do?reportId=c26aafb8-4a24-4624-853d-9e0343f0249e
# TODO 2019  https://innocomreport2.chinatorch.org.cn/xinnocommgr/reportdeal/CertificateValidity/showDetails.do?reportId=aa4e980e-3c89-4f91-89c6-6bf4a3bc4f1e


def get_content(driver=None):
    try:
        WritePSForm = list()
        i = 1
        while True:
            # if p_index != 1:
            #     page_objs = bm.get_page_num(driver=driver)
            #     page_objs[p_index - 1].click()

            # record_loc = (By.CSS_SELECTOR, 'tbody.tableBody tr')
            # records = driver.find_elements(*record_loc)
            text = driver.page_source
            tree = etree.HTML(text)
            records = tree.xpath("//tbody[@class='tableBody']/tr")
            for r_index, r in enumerate(records, 1):
                operate_btn_loc = (By.CSS_SELECTOR, f'tbody.tableBody tr:nth-of-type({r_index}) td:last-child a')
                if g.full_verify is True:
                    bm.wait(driver=driver, ele_loc=operate_btn_loc)
                    driver.find_element(*operate_btn_loc).click()

                    text = driver.page_source

                    ps_info = parse_data(driver=driver, text=text)
                    WritePSForm.append(ps_info)
                    # if i != 1 and r_index != 1:
                    if i != 1:
                        # 跳转到第 i 页
                        show_last_page_btn_loc = (
                        By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a:nth-of-type(5)")
                        start_page = 5
                        while True:
                            # if i > start_page:
                            #     bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            if i > start_page:
                                start_page += 2
                                bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            else:
                                aim_page = (
                                By.XPATH, """//ul[@class='pagination pull-right']/li[3]/a[text() = '{}']""".format(i))
                                bm.click(driver=driver, ele_loc=aim_page)
                                break

                        bm.wait(driver=driver, ele_loc=g.table_loc)
                else:
                    ps_item = dict()
                    ps_id = bm.get_ids(r.xpath("./td[2]/text()"))
                    ps_item["ps_id"] = ps_id
                    ps_name = bm.get_first(r.xpath("./td[3]/text()"))
                    ps_item["ps_name"] = ps_name
                    tech_fieldname = bm.handle_domain(r.xpath("./td[4]/text()"))
                    ps_item["tech_fieldname"] = tech_fieldname
                    sales_revenue = bm.get_float_str(r.xpath("./td[5]/text()"))
                    ps_item["sales_revenue"] = sales_revenue
                    is_major = bm.get_first(r.xpath("./td[6]/text()"))
                    ps_item["is_major"] = is_major
                    ipr_ids = bm.get_ids(r.xpath("./td[7]/text()"))
                    ps_item["ipr_ids"] = ipr_ids
                    WritePSForm.append(ps_item)
            next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
            onclick = None
            try:
                onclick = next_btn.get_attribute("onclick")
            except Exception as err:
                g.logger.error("get next page button\' attribute error: {}".format(err))
            if onclick is None:
                # driver.switch_to.default_content()
                break
            else:
                bm.click(driver=driver, ele_loc=g.next_btn_loc)
                bm.wait(driver=driver, ele_loc=g.table_loc)
                i += 1
        return {"key": "WritePSForm", "value": WritePSForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_ps(driver=None):
    try:
        ps_loc = (By.LINK_TEXT, '上年度高新技术产品（服务）情况表')

        bm.detail_switch_iframe(driver=driver)

        bm.wait(driver=driver, ele_loc=ps_loc)
        driver.find_element(*ps_loc).click()

        bm.wait(driver=driver, ele_loc=g.title_loc)

        get_content(driver=driver)
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


#
def parse_data(driver=None, text=''):
    try:
        text = text.replace('<div class="line"></div>', '')
        tree = etree.HTML(text)
        ps_item = {'ps_id': '', 'ps_name': '', 'tech_fieldlist': '', 'tech_fieldname': '',
                   'tech_source': '', 'sales_revenue': '', 'is_major': '', 'ipr_ids': '', 'keytech_ind': '',
                   'caosp': '', 'aipr_tsp': ''}

        ps_id_name = tree.xpath('//input[@id="cod"]/@value')
        ps_item['ps_id'] = bm.get_ids(ps_id_name)

        # business_case = get_first(tree.xpath('//div[@class="box-body"]'))

        ps_name = tree.xpath('//input[@id="productName"]/@value')
        ps_item['ps_name'] = bm.join_and_repalce(ps_name)
        domain1 = bm.get_first(tree.xpath("//div[@id='uniform-onemain']/span/text()"))
        domain2 = bm.get_first(tree.xpath("//div[@id='uniform-scdmain']/span/text()"))
        domain3 = bm.get_first(tree.xpath("//div[@id='uniform-thdmain']/span/text()"))
        domain = ",".join([domain1, domain2, domain3])

        ps_item['tech_fieldname'] = domain

        tech_source_name = tree.xpath('//div[@id="uniform-technologyS"]/span/text()')
        ps_item['tech_source'] = tech_source_name

        sales_revenue = tree.xpath('//input[@id="shr"]/@value')
        ps_item['sales_revenue'] = bm.get_float_str(sales_revenue)
        # # 匹配汉字， 根据 是或否 返回 0， 1
        is_major_name = tree.xpath('//input[@checked="checked"]/@value')
        ps_item['is_major'] = 0 if is_major_name == "0" else 1
        # # 使用 bm.get_ids
        ipr_str = tree.xpath('//textarea[@id="yxZscqbh"]/text()')
        ps_item['ipr_ids'] = bm.get_ids(id_str=ipr_str)

        # # # TODO 一下三个字段使用一个处理方法。剔除没有汉字的元素。
        keytech_ind = tree.xpath('//textarea[@id="PGjjszb"]/text()')
        ps_item['keytech_ind'] = bm.handel_long_text(keytech_ind)
        caosp = tree.xpath('//textarea[@id="PJzys"]/text()')
        ps_item['caosp'] = bm.handel_long_text(caosp)
        aipr_tsp = tree.xpath('//textarea[@id="PZscqqk"]/text()')
        ps_item['aipr_tsp'] = bm.handel_long_text(aipr_tsp)

        # # #  点击返回列表按钮。
        back_list_loc = (By.CSS_SELECTOR, 'h2.text-center a.left-b')
        bm.wait(driver=driver, ele_loc=back_list_loc)
        driver.find_element(*back_list_loc).click()
        return ps_item
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)
